package com.pureut.storage.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.datascope.annotation.DataScope;
import com.pureut.common.security.utils.DictUtils;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.storage.domain.*;
import com.pureut.storage.domain.order.domain.CustomerManagement;
import com.pureut.storage.domain.system.domain.SysDocument;
import com.pureut.storage.dto.*;
import com.pureut.storage.export.SalesReturnExport;
import com.pureut.storage.mapper.*;
import com.pureut.storage.service.*;
import com.pureut.storage.utils.DocumentTypeEnum;
import com.pureut.storage.utils.GenerationMethodEnum;
import com.pureut.storage.vo.PickingRestDbVo;
import com.pureut.storage.vo.SalesReturnVo;
import com.pureut.storage.vo.SalesVo;
import com.pureut.storage.vo.UpdateStatusByQualityVo;
import com.pureut.system.api.*;
import com.pureut.system.api.domain.SysDictData;
import com.pureut.system.api.domain.SysUser;
import com.pureut.system.api.vo.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/***
 *
 * Author:C
 * Date:2022/12/29 11:12
 * @DESC
 */
@Service
public class SalesReturnServiceImpl extends ServiceImpl<SalesReturnMapper, SalesReturn> implements SalesReturnService {

    @Resource
    SalesReturnMapper salesReturnMapper;

    @Resource
    OrderFeignService orderFeignService;

    @Resource
    FeignService feignService;

    @Resource
    WarehouseService warehouseService;

    @Resource
    SystemDocumentFeignService systemDocumentFeignService;

    @Resource
    SalesReturnDetailService salesReturnDetailService;

    @Resource
    SalesReturnDetailMapper salesReturnDetailMapper;

    @Resource
    WmsStockInfoMapper wmsStockInfoMapper;

    @Resource
    WmsStockInfoService wmsStockInfoService;

    @Resource
    PublicGoodsMapper publicGoodsMapper;

    //用户信息
    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    PickingSaleDetailMapper pickingSaleDetailMapper;

    @Resource
    PickingSaleMapper pickingSaleMapper;

    @Resource
    QualityFeginService qualityFeginService;

    @Resource
    CustomerManagementService customerManagementService;

    @Resource
    OutboundLogService outboundLogService;

    @Resource
    OutboundLogMapper outboundLogMapper;


    /**
     * 销售退货列表
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    @DataScope(deptAlias = "a")
    public List<SalesReturnDto> getSalesList(SalesReturnVo salesReturnVo) {
        List<SalesReturnDto> saleList = salesReturnMapper.getSaleList(salesReturnVo);
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取销售退货状态字典值
        List<SysDictData> saleArray = DictUtils.getDictCache("sales_return_status");
        Map<String, String> saleStatusMap = saleArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取销售退货收发类型
        List<SysDictData> rdArray = DictUtils.getDictCache("sales_return_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        for (SalesReturnDto entity : saleList) {
            //状态
            entity.setStatusDict(saleStatusMap.get(entity.getStatus()));
            //单据类型
            entity.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(entity.getDocumentType())));
            //收发类型
            entity.setReceiveTypeDict(rdMap.get(String.valueOf(entity.getReceiveType())));
            //生成方式
            entity.setGenerationMethodDict(GenerationMethodEnum.getValue(Integer.parseInt(entity.getGenerationMethod())));
            //单位
            entity.setMaterialUnitDict(unitMap.get(entity.getMaterialUnit()));
        }
        return saleList;
    }

    /**
     * 销售退货新增
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public boolean addSalesReceipt(SalesReturnVo salesReturnVo) throws Exception {
        List<SalesVo> salesList = salesReturnVo.getSalesList();
        if (salesList.size() == 0) {
            throw new GlobalException("至少存在一条数据");
        }
        List<SalesReturn> salesReturnList = new ArrayList<>();
        for (SalesVo entity : salesList) {
            SalesReturn salesReturn = new SalesReturn();
            String authorityCoding = feignService.getAuthorityCoding("warehouse:warehousing:saleReturn:list");
            if (authorityCoding == null) {
                throw new GlobalException("该单据未进行配置，无法生成单据编码");
            }
            salesReturn.setReceiptNo(authorityCoding)
                    .setDeptId(SecurityUtils.getDeptId())
                    .setStatus(1)
                    .setSaleOrderNo(entity.getSaleOrderNo())
                    .setWarehousTime(salesReturnVo.getWarehousTime())
                    .setMaterialId(entity.getMaterialId())
                    .setMaterialCategory(entity.getMaterialCategory())
                    .setMaterialCode(entity.getMaterialCode())
                    .setCustomerId(salesReturnVo.getCustomerId())
                    .setBackWeight(entity.getBackWeight())
                    .setShippedWeight(entity.getShippedWeight())
                    .setWarehousingWarehouse(entity.getWarehousingWarehouse())
                    .setDocumentType(DocumentTypeEnum.SALES_RETURN.getCode())
                    .setReceiveType(salesReturnVo.getReceiveType())
                    .setGenerationMethod(GenerationMethodEnum.MANUALLY_GENERATED.getCode())
                    .setRemark(salesReturnVo.getRemark())
                    .setDrawerBy(SecurityUtils.getUsername())
                    .setDrawerTime(new Date());
            salesReturnList.add(salesReturn);
        }
        return saveBatch(salesReturnList);
    }

    /**
     * 关结
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public boolean close(SalesReturnVo salesReturnVo) {
        SalesReturn salesReturn = getById(salesReturnVo.getId());

        //已完成、已关结不可重复关结；
        if (salesReturn.getStatus() != 5 || salesReturn.getStatus() != 6) {
            //待检验状态的单据关结后，单据状态更新为“已关结”，跳过后续操作，入库的物料显示为在库，关联的品质检验单状态更新为“已撤销”；
            if (salesReturn.getStatus() == 3) {
                List<SalesReturnDetail> salesReturnDetails = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = salesReturnDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 1)
                        .map(SalesReturnDetail::getMaterialNumber)
                        .collect(Collectors.toList());

                if (!materialNumberList.isEmpty()) {

                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }

                wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
                //修改对应品质检验单状态为已撤销
                UpdateQualityStatusVo updateQualityStatusVo = new UpdateQualityStatusVo();
                updateQualityStatusVo.setAssociatedNo(salesReturn.getReceiptNo());
                updateQualityStatusVo.setStatus(8);
                qualityFeginService.updateQualityInspectionDocument(updateQualityStatusVo);
            }
            //待交接状态的单据关结后，单据状态更新为“已关结”，跳过后续操作，入库的物料显示在库
            if (salesReturn.getStatus() == 4) {
                List<SalesReturnDetail> salesReturnDetails = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = salesReturnDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 1)
                        .map(SalesReturnDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                if (!materialNumberList.isEmpty()) {
                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
            }
            //待入库、部分入库状态的单据关结后，单据状态更新为“已关结”，无影响；
            //入库中的单据关结后，单据状态更新为“已关结”，已扫描过的条码为在库
            if (salesReturn.getStatus() == 2) {
                List<SalesReturnDetail> salesReturnDetails = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
                //获取该单据下明细数据物料号码
                List<String> materialNumberList = salesReturnDetails.stream()
                        .filter(entity -> entity.getStatus() == 2 && entity.getStatus() == 1)
                        .map(SalesReturnDetail::getMaterialNumber)
                        .collect(Collectors.toList());
                if (!materialNumberList.isEmpty()) {
                    List<WmsStockInfo> wmsStockInfos = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().in(WmsStockInfo::getWsiMaterialNumber, materialNumberList));
                    for (WmsStockInfo wmsStockInfo : wmsStockInfos) {
                        wmsStockInfo.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfos);
                }
            }
            salesReturn.setStatus(6)
                    .setCloseReason(salesReturnVo.getCloseReason())
                    .setClosingBy(SecurityUtils.getUsername())
                    .setClosingTime(new Date());
        } else {
            throw new GlobalException("已完成、已关结不可重复关结");
        }

        return updateById(salesReturn);


    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public SalesReturnDto getView(Long id) {

        SalesReturnDto saleById = salesReturnMapper.getSaleById(id);

        //获取收发类型字典值
        List<SysDictData> typeArray = DictUtils.getDictCache("sales_return_rd_type");
        Map<String, String> salesReturnMap = typeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单位
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //单据类型
        saleById.setDocumentTypeDict(DocumentTypeEnum.getValue(Integer.parseInt(saleById.getDocumentType())));
        //收发类型
        saleById.setReceiveTypeDict(salesReturnMap.get(String.valueOf(saleById.getReceiveType())));

        //列表
        List<ViewDto> viewDtos = new ArrayList<>();
        ViewDto viewDto = new ViewDto();
        viewDto.setSaleOrderNo(saleById.getSaleOrderNo());
        viewDto.setShippedWeight(saleById.getShippedWeight());
        viewDto.setBackWeight(saleById.getBackWeight());
        viewDto.setMaterialName(saleById.getMaterialName());
        viewDto.setMaterialCode(saleById.getMaterialCode());
        viewDto.setMaterialSpec(saleById.getMaterialSpec());
        viewDto.setMaterialUnit(saleById.getMaterialUnit());
        viewDto.setMaterialUnitDict(unitMap.get(saleById.getMaterialUnit()));

        //入库仓
        WarehouseDto view = warehouseService.getView(saleById.getWarehousingWarehouse());
        if (view != null) {
            viewDto.setWarehousingWarehouse(String.valueOf(saleById.getWarehousingWarehouse()));
            viewDto.setWarehouseName(view.getWarehouseName());
        }
        viewDtos.add(viewDto);
        saleById.setViewList(viewDtos);
        return saleById;
    }


    /**
     * 修改
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public boolean updateSalesReceipt(SalesReturnVo salesReturnVo) {
        SalesReturn salesReturn = getById(salesReturnVo.getId());
        if (salesReturn.getStatus() == 1) {
            salesReturn.setReceiveType(salesReturnVo.getReceiveType());
            salesReturn.setCustomerId(salesReturnVo.getCustomerId());
            salesReturn.setWarehousTime(salesReturnVo.getWarehousTime());
            salesReturn.setRemark(salesReturnVo.getRemark());
            List<SalesVo> salesList = salesReturnVo.getSalesList();
            for (SalesVo entity : salesList) {
                salesReturn.setBackWeight(entity.getBackWeight())
                        .setWarehousingWarehouse(entity.getWarehousingWarehouse());
            }
            return updateById(salesReturn);
        } else {
            throw new GlobalException("只能修改待入库的数据");
        }
    }

    /**
     * 删除
     *
     * @param idStr
     * @return
     */
    @Override
    public boolean deleteSalesReceipt(String idStr) {
        List<String> idList = Arrays.asList(idStr.split(","));
        if (idList.size() == 0) {
            throw new GlobalException("至少勾选一条数据");
        }
        List<SalesReturn> salesReturns = new ArrayList<>();
        List<SalesReturn> salesReturnList = salesReturnMapper.selectList(new QueryWrapper<SalesReturn>().lambda().in(SalesReturn::getId, idList));
        for (SalesReturn entity : salesReturnList) {
            if (entity.getStatus() == 1) {
                salesReturns.add(entity);
            } else {
                throw new GlobalException("只能删除待入库的单据");
            }
        }
        List<SalesReturn> deleteList = new ArrayList<>();
        for (SalesReturn entity : salesReturns) {
            if (entity.getGenerationMethod() == 2) {
                deleteList.add(entity);
            } else {
                throw new GlobalException("自动生成的单据不能删除");
            }
        }
        return removeByIds(deleteList);
    }

    /**
     * 导出
     *
     * @param salesReturnVo
     * @return
     */
    @Override
    public List<SalesReturnExport> getInfoExport(SalesReturnVo salesReturnVo) {
        List<SalesReturnExportDto> salesReturnList = null;

        if (salesReturnVo.getIdStr() == null) {
            salesReturnList = salesReturnMapper.getSaleListOut(salesReturnVo);
        } else {
            List<String> idList = Arrays.asList(salesReturnVo.getIdStr().split(","));
            //获取销售退货列表
            salesReturnList = salesReturnMapper.getDataByIdStr(idList);
        }
        //获取网型标准缓存字典数据
        List<SysDictData> netArray = DictUtils.getDictCache("sys_of_type");
        Map<String, String> netMap = netArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        //获取铺网类型标准缓存字典数据
        List<SysDictData> netTypeArray = DictUtils.getDictCache("sys_type_net");
        Map<String, String> netTypeMap = netTypeArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        //销售退货收发类型字典数据
        List<SysDictData> rdArray = DictUtils.getDictCache("sales_return_rd_type");
        Map<String, String> rdMap = rdArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        List<SalesReturnExport> salesReturnExportList = new ArrayList<>();
        for (SalesReturnExportDto entity : salesReturnList) {
            SalesReturnExport salesReturnExport = new SalesReturnExport();

            BeanUtils.copyProperties(entity, salesReturnExport);
            //收发类型
            if(!"0".equals(entity.getReceiveType())){
                salesReturnExport.setReceiveType(rdMap.get(String.valueOf(entity.getReceiveType())));
            }else {
                salesReturnExport.setReceiveType("");
            }
            salesReturnExport.setMaterialNetDict(netMap.get(entity.getMaterialNetDict()));
            salesReturnExport.setMaterialNetTypeDict(netTypeMap.get(entity.getMaterialNetTypeDict()));
            salesReturnExportList.add(salesReturnExport);
        }
        return salesReturnExportList;
    }


    /**
     * 销售退货pda
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestDbDto salesReturnPda(PickingRestDbVo pickingRestDbVo) throws Exception {
        PickingRestDbDto pickingRestDbDto = new PickingRestDbDto();
        SalesReturn salesReturn = getById(pickingRestDbVo.getId());
        if (salesReturn.getStatus() == 1 || salesReturn.getStatus() == 2) {
            //扫码入库
            if ("1".equals(pickingRestDbVo.getType())) {
                //如果是第一步，需要查询库位信息
                if (pickingRestDbVo.getExecutionOrder() == 1) {
                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
                    if (warehouseCode.getCombinationName() == null) {
                        pickingRestDbDto.setMessage("没有该仓库信息，请核实!");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
                    pickingRestDbDto.setMessage("操作成功");
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }
                //如果是第二步，需要根据物料号码查询销售发货（出库模块）明细信息
                if (pickingRestDbVo.getExecutionOrder() == 2) {
                    //获取销售退货列表
                    SalesReturnVo salesReturnVo = new SalesReturnVo();
                    List<SalesReturnDto> saleList = salesReturnMapper.getSaleList(salesReturnVo);
                    SalesReturn byId = getById(pickingRestDbVo.getId());
                    //获取明细对象
//                    SalesReturnDetail salesReturnDetailObject = pickingRestDbVo.getSalesReturnObject();
                    PickingSaleDetail pickingSaleDetail = pickingSaleDetailMapper.selectOne(new QueryWrapper<PickingSaleDetail>().lambda().eq(PickingSaleDetail::getPdoductNumber, pickingRestDbVo.getInputValue()));
                    if (pickingSaleDetail == null) {
                        pickingRestDbDto.setCode("500");
                        pickingRestDbDto.setMessage("没有查询到对应物料，请核实后输入!");
                        return pickingRestDbDto;
                    }

                    //查询该物料是否入库过
                    WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()));

                    if (wmsStockInfo != null) {
                        pickingRestDbDto.setMessage("该数据已经入库");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }


                    Long menuId = feignService.getIdByMenuName("销售退货");
                    AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
                    SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
                    SalesReturnDetail salesReturnDetail = new SalesReturnDetail();
                    PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));

                    //如果配置了送检,则校验是否配了检验方案
                    if (sysDocument.getDocInspectionMark()==1){

                        List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                        if (documentCheckDtoList==null){
                            throw new GlobalException("请先在单据配置中配置送检方案");
                        }

                        QualitySchemeConfigurationVo qualitySchemeConfigurationVo = new QualitySchemeConfigurationVo();
                        qualitySchemeConfigurationVo.setCategory(publicGoods.getMaterialCategory());
                        qualitySchemeConfigurationVo.setItemRank(documentCheckDtoList.get(0).getCheckSubmit());
                        qualitySchemeConfigurationVo.setMaterialCategory(publicGoods.getMaterialType());
                        qualitySchemeConfigurationVo.setMaterialCode(pickingSaleDetail.getItemCode());
                        boolean check = qualityFeginService.check(qualitySchemeConfigurationVo);

                        if (!check){
                            throw new GlobalException("该物料不存在对应的检验方案");

                        }
                    }


                    //根据扫描的物料编码和入库列表数据进行比对
//                    for (SalesReturnDto entity : saleList) {
                    //如果对应的编码相等，就将该明细存入
                    if (byId.getMaterialCode().equals(pickingSaleDetail.getItemCode())) {
                        //是否配置了送检
                        if (sysDocument.getDocInspectionMark() == 1) {
                            //修改明细状态为待送检
                            salesReturnDetail.setStatus(1);
                        } else {
                            //修改明细状态为待交接
                            salesReturnDetail.setStatus(2);
                        }
                        salesReturnDetail.setSalesReturnId(byId.getId());
                        salesReturnDetail.setMaterialCode(pickingSaleDetail.getItemCode());
                        salesReturnDetail.setMaterialNumber(pickingRestDbVo.getInputValue());
                        salesReturnDetail.setGrossWeight(pickingSaleDetail.getGrossWeight());
                        salesReturnDetail.setNetWeight(pickingSaleDetail.getNetWeight());
                        salesReturnDetail.setReceiptQuantity(1);
                        salesReturnDetail.setBatchNo(pickingSaleDetail.getBatchNumber());
                        salesReturnDetail.setWarehouseMessage(pickingRestDbVo.getCombinationName());
                        salesReturnDetail.setWarehouseInBy(SecurityUtils.getUsername());
                        salesReturnDetail.setWarehouseInTime(new Date());
                        boolean save = salesReturnDetailService.save(salesReturnDetail);
                        if (save) {
                            //向仓库表中添加对应的数据
                            WmsStockInfo wmsStockInfo1 = new WmsStockInfo();

                            OutboundLog outboundLog = outboundLogMapper.selectOne(new QueryWrapper<OutboundLog>().lambda().eq(OutboundLog::getWsiMaterialNumber, salesReturnDetail.getMaterialNumber()));

                            BeanUtils.copyProperties(outboundLog, wmsStockInfo1, new String[]{"id"});

                            wmsStockInfo1.setWsiMaterialStatus(2);
                            wmsStockInfo1.setWsiWarehourse(String.valueOf(pickingRestDbVo.getCkId()));
                            wmsStockInfo1.setWsiReservoirArea(String.valueOf(pickingRestDbVo.getKqId()));
                            wmsStockInfo1.setWsiStorageLoaction(String.valueOf(pickingRestDbVo.getKwId()));
                            wmsStockInfo1.setWsiWarehourseInfo(pickingRestDbVo.getCombinationName());
                            wmsStockInfo1.setWsiDocNum(byId.getReceiptNo());
                            wmsStockInfo1.setWsiCategory(String.valueOf(publicGoods.getMaterialCategory()));
                            wmsStockInfo1.setWsiMaterialType(publicGoods.getMaterialType());
                            wmsStockInfo1.setWsiReveiveTime(new Date());
                            wmsStockInfo1.setWsiConnectNum(byId.getSaleOrderNo());
                            wmsStockInfo1.setWsiMaterialGrade("1");
                            wmsStockInfoService.save(wmsStockInfo1);
                        }
                    }


                    //获取单位字典值
                    List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                    Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                    //判断改物料是否和单据物料一致
                    boolean a = publicGoods.getMaterialCode().equals(salesReturn.getMaterialCode());
                    if (!a) {
                        pickingRestDbDto.setMessage("入库物料和单据物料不一致，无法入库");
                        pickingRestDbDto.setCode("500");
                        return pickingRestDbDto;
                    }
                    //判断单位
                    if ("2".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是千克
                        if (salesReturn.getActualQuantity() == null || "".equals(salesReturn.getActualQuantity())) {
                            salesReturn.setActualQuantity(String.valueOf(salesReturnDetail.getNetWeight()));
                            //修改采购入库信息入库重量
                            salesReturn.setWarehousingWeight(salesReturnDetail.getNetWeight());
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(salesReturn.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            String s = bigDecimal.add(bigDecimal1).toString();
                            salesReturn.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else if ("3".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                        if (salesReturn.getActualQuantity() == null || "".equals(salesReturn.getActualQuantity())) {
                            BigDecimal bigDecimal = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            BigDecimal divide = bigDecimal.divide(new BigDecimal("1000"));
                            salesReturn.setActualQuantity(divide.toString());
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(salesReturn.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            BigDecimal divide = bigDecimal1.divide(new BigDecimal("1000"));
                            String s = bigDecimal.add(divide).toString();
                            salesReturn.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    } else {
                        if (salesReturn.getActualQuantity() == null || "".equals(salesReturn.getActualQuantity())) {
                            salesReturn.setActualQuantity(String.valueOf(salesReturnDetail.getReceiptQuantity()));
                            //修改采购入库信息入库重量
                            salesReturn.setWarehousingWeight(salesReturnDetail.getNetWeight());
                        } else {
                            BigDecimal bigDecimal = new BigDecimal(salesReturn.getActualQuantity());
                            BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getReceiptQuantity()));
                            String s = bigDecimal.add(bigDecimal1).toString();
                            salesReturn.setActualQuantity(s);
                            //修改采购入库信息入库重量
                            BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                            BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                            String s1 = bigDecimal2.add(bigDecimal3).toString();
                            salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                        }
                    }
                    //将入库数量+1
                    int warehousingNum = salesReturn.getWarehousingNum();
                    if (warehousingNum == 0) {
                        salesReturn.setWarehousingNum(1);
                    } else {
                        salesReturn.setWarehousingNum(warehousingNum + 1);
                    }

                    pickingRestDbDto.setQuantityIdentification(salesReturn.getBackWeight() + "/" + salesReturn.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setMessage("物料号码:" + pickingRestDbVo.getInputValue() + "," + "净重:" + pickingSaleDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + "1" + "," + "录入成功");
                    pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                    pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestDbDto.setWarehouseNumber(String.valueOf(salesReturn.getWarehousingNum()));


                    double aDouble = Double.parseDouble(salesReturn.getActualQuantity());
                    double backWeight = salesReturn.getBackWeight();

                    //判断是否配置了超收
                    if (sysDocument.getDocExcessMark() == 2 && publicGoods.getMaterialClosed() == 2) {
                        if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(backWeight)) {
                            //如果配置了送检
                            if (sysDocument.getDocInspectionMark() == 1) {
                                salesReturn.setStatus(3);
                                updateById(salesReturn);
                                // 生成品质检验单
                                if (sysDocument.getDocCode() == null) {
                                    throw new GlobalException("未进行单据配置");
                                }
                                List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
                                if (documentCheckDtoList.size() < 1) {
                                    throw new GlobalException("未进行检验单生成配置");
                                }
                                //通过物料编码获取物料类别
                                //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
                                //获取明细列表
                                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
                                StringBuilder stringBuilder = new StringBuilder();
                                for (SalesReturnDetail entity : salesReturnDetailList) {
                                    stringBuilder.append(entity.getBatchNo()).append(",");
                                }
                                StringBuilder stringBuilder1 = stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                                CustomerManagement customerManagement = customerManagementService.getById(salesReturn.getCustomerId());

                                for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                                    if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                                        QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                                        qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                                        qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                                        qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                                        qualityInspectionDocumentVo.setMaterialCode(salesReturn.getMaterialCode());
                                        qualityInspectionDocumentVo.setBatchNo(stringBuilder1.toString());
                                        qualityInspectionDocumentVo.setAssociatedNo(salesReturn.getReceiptNo());
                                        qualityInspectionDocumentVo.setDifferentString(customerManagement.getCustomerNum());
                                        qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                                        qualityInspectionDocumentVo.setModeType(12);

                                        List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                                        for (SalesReturnDetail entity : salesReturnDetailList) {
                                            MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                                            materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                                            materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                                            materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                                        }
                                        qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

//                                        AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
                                        boolean b = qualityFeginService.addWares(qualityInspectionDocumentVo);
//                                        String code = add.get("code").toString();
                                        if (!b) {
                                            pickingRestDbDto.setMessage("生成品质检验单失败");
                                            pickingRestDbDto.setCode("500");
                                            return pickingRestDbDto;
                                        }
                                    }
                                }
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            }
                            //如果配置了交接
                            if (sysDocument.getDocHandoverMark() == 1) {
                                salesReturn.setStatus(4);
                                updateById(salesReturn);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            } else {
                                salesReturn.setStatus(5);
                                updateById(salesReturn);
                                pickingRestDbDto.setCode("200");
                                return pickingRestDbDto;
                            }
                        }
                    }
                    //回传销售退货
                    BackDataVo backDataVo = new BackDataVo();
                    PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda().eq(PickingSale::getWodDocNum, byId.getSaleOrderNo()));
                    backDataVo.setSaleNumber(pickingSale.getConnectionId());
                    backDataVo.setMaterialCode(byId.getMaterialCode());
                    backDataVo.setNetWeight(pickingSaleDetail.getNetWeight());
                    boolean b = orderFeignService.updateShippingOutWeight(backDataVo);
                    if (!b) {
                        throw new GlobalException("服务调用失败");
                    }

                    salesReturn.setStatus(2);
                    updateById(salesReturn);
                    pickingRestDbDto.setCode("200");
                    return pickingRestDbDto;
                }


            }
            //条码撤销
            if ("2".equals(pickingRestDbVo.getType())) {
//                //如果是第一步，需要查询库位信息
//                if (pickingRestDbVo.getExecutionOrder() == 1) {
//                    WarehouseStringDto warehouseCode = warehouseService.getWarehouseCode(pickingRestDbVo.getInputValue());
//                    if (warehouseCode.getCombinationName() == null) {
//                        pickingRestDbDto.setMessage("没有该仓库信息，请核实!");
//                        pickingRestDbDto.setCode("500");
//                        return pickingRestDbDto;
//                    }
//                    pickingRestDbDto.setWarehouseMessage(warehouseCode.getCombinationName());
//                    pickingRestDbDto.setCkId(warehouseCode.getCkId());
//                    pickingRestDbDto.setKqId(warehouseCode.getKqId());
//                    pickingRestDbDto.setKwId(warehouseCode.getKwId());
//                    pickingRestDbDto.setMessage("操作成功");
//                    pickingRestDbDto.setCode("200");
//                    return pickingRestDbDto;
//                }
                //如果是第二步，需要根据物料号码查询明细信息
//                if (pickingRestDbVo.getExecutionOrder() == 2) {
                //查询该条码是否扫描过
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, pickingRestDbVo.getInputValue()));
                if (wmsStockInfo == null) {
                    pickingRestDbDto.setMessage("撤销失败，请核实后再录入");
                    pickingRestDbDto.setCode("500");
                    return pickingRestDbDto;
                }
                wmsStockInfoMapper.deleteById(wmsStockInfo);

                //同时删除采购入库明细状态
                SalesReturnDetail salesReturnDetail = salesReturnDetailMapper.selectOne(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));

                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, salesReturn.getMaterialCode()));
                //获取单位字典值
                List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
                Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
                //设置返回信息
                pickingRestDbDto.setMessage("物料号码:" + salesReturnDetail.getMaterialNumber() + "," + "净重:" + salesReturnDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + salesReturnDetail.getReceiptQuantity() + "," + "撤销成功");
                pickingRestDbDto.setQuantityIdentification(salesReturn.getBackWeight() + "/" + salesReturn.getActualQuantity() + unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestDbDto.setUnit(publicGoods.getMaterialUnit());
                pickingRestDbDto.setUnitDict(unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestDbDto.setWarehouseNumber(String.valueOf(salesReturn.getWarehousingNum()));

                salesReturnDetailMapper.deleteById(salesReturnDetail);
                List<SalesReturnDetail> list = salesReturnDetailService.list();
                //判断条数修改采购入库状态
                if (list.size() == 0) {
                    salesReturn.setStatus(1);
                    salesReturn.setWarehousingNum(0);
                    salesReturn.setWarehousingWeight(0);
                    salesReturn.setActualQuantity("0");
                } else {
                    salesReturn.setWarehousingNum(salesReturn.getWarehousingNum() - 1);
                    //判断单位
                    BigDecimal bigDecimal = new BigDecimal(salesReturn.getActualQuantity());
                    BigDecimal bigDecimal1;
                    if ("2".equals(publicGoods.getMaterialUnit())) {
                        //如果是千克
                        bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                        String s = bigDecimal.subtract(bigDecimal1).toString();
                        salesReturn.setActualQuantity(s);
                        //修改采购入库信息入库重量
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                        BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                        String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                        salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                        //入库数量
                    } else if ("3".equals(publicGoods.getMaterialUnit())) {
                        //如果单位是吨，若单位为吨，则实际量=入库重量（kg）/1000
                        BigDecimal bigDecimalNetWeight = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                        BigDecimal divide = bigDecimalNetWeight.divide(new BigDecimal("1000"));
                        String s = bigDecimal.subtract(divide).toString();
                        salesReturn.setActualQuantity(s);
                        //修改采购入库信息入库重量
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                        BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                        String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                        salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                    } else {
                        bigDecimal1 = new BigDecimal(String.valueOf(salesReturnDetail.getReceiptQuantity()));
                        String s = bigDecimal.subtract(bigDecimal1).toString();
                        salesReturn.setActualQuantity(s);
                        //修改采购入库信息入库重量
                        BigDecimal bigDecimal2 = new BigDecimal(String.valueOf(salesReturn.getWarehousingWeight()));
                        BigDecimal bigDecimal3 = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight()));
                        String s1 = bigDecimal2.subtract(bigDecimal3).toString();
                        salesReturn.setWarehousingWeight(Double.parseDouble(s1));
                    }
                    //入库数量
                    salesReturn.setWarehousingNum(salesReturn.getWarehousingNum() - 1);

                    //回传销售退货
                    BackDataVo backDataVo = new BackDataVo();
                    PickingSale pickingSale = pickingSaleMapper.selectOne(new QueryWrapper<PickingSale>().lambda().eq(PickingSale::getWodDocNum, salesReturn.getSaleOrderNo()));
                    backDataVo.setSaleNumber(pickingSale.getConnectionId());
                    backDataVo.setMaterialCode(salesReturn.getMaterialCode());
                    backDataVo.setNetWeight(salesReturnDetail.getNetWeight());
                    boolean b = orderFeignService.updateShippingOutWeight(backDataVo);
                    if (!b) {
                        throw new GlobalException("服务调用失败");
                    }

                }
                updateById(salesReturn);
                pickingRestDbDto.setCode("200");
                return pickingRestDbDto;
//                }
            }
        } else {
            pickingRestDbDto.setMessage("只能操作待入库和入库中得数据");
            pickingRestDbDto.setCode("500");
            return pickingRestDbDto;
        }
        pickingRestDbDto.setMessage("步骤不正确,请核实!");
        pickingRestDbDto.setCode("500");
        return pickingRestDbDto;
    }

    /**
     * 销售退货拣货撤销
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCancellation(PickingRestDbVo pickingRestDbVo) {
        //根据其它入库id获取明细数据
        List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
        //根据批次号查询仓库信息
        List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, salesReturnDetailList.get(0).getBatchNo()));
        //删除仓储数据
        wmsStockInfoMapper.deleteBatchIds(wmsStockInfoList);
        //删除明细数据
        salesReturnDetailMapper.deleteBatchIds(salesReturnDetailList);
        //修改销售退货状态
        SalesReturn salesReturn = getById(pickingRestDbVo.getId());
        salesReturn.setStatus(1);
        salesReturn.setWarehousingNum(0);
        salesReturn.setWarehousingWeight(0);
        salesReturn.setActualQuantity("0");
        //删除关联的检验单
        String relevanceDoc = salesReturn.getReceiptNo();
        qualityFeginService.removeDoc(relevanceDoc);
        return updateById(salesReturn);
    }

    /**
     * 销售退货拣货完成
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean pickingCompleted(PickingRestDbVo pickingRestDbVo) throws Exception {
        SalesReturn salesReturn = getById(pickingRestDbVo.getId());
        if (salesReturn.getStatus() == 5) {
            throw new GlobalException("不能对已完成的单据进行拣货完成");
        }
        CustomerManagement customerManagement = customerManagementService.getById(salesReturn.getCustomerId());
//        //需求量
//        double aDouble = Double.parseDouble(salesReturn.getActualQuantity());
//        //退货量
//        double backWeight = salesReturn.getBackWeight();

        PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, salesReturn.getMaterialCode()));

        Long menuId = feignService.getIdByMenuName("销售退货");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //配置了超收
//        if (sysDocument.getDocExcessMark() == 1 && publicGoods.getMaterialClosed() == 1) {
//            if (Double.doubleToLongBits(aDouble) >= Double.doubleToLongBits(backWeight)) {
        //如果配置了送检
        if (sysDocument.getDocInspectionMark() == 1) {
            salesReturn.setStatus(3);
            // 生成品质检验单
            if (sysDocument.getDocCode() == null) {
                throw new GlobalException("未进行单据配置");
            }
            List<SysDocumentCheckDto> documentCheckDtoList = sysDocument.getDocumentCheckDtoList();
            if (documentCheckDtoList.size() < 1) {
                throw new GlobalException("未进行检验单生成配置");
            }
            //通过物料编码获取物料类别
            //PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, pickingSaleDetail.getItemCode()));
            //获取明细列表
            List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
            StringBuilder stringBuilder = new StringBuilder();
            for (SalesReturnDetail entity : salesReturnDetailList) {
                stringBuilder.append(entity.getBatchNo()).append(",");
            }
            StringBuilder stringBuilderBatch = stringBuilder.deleteCharAt(stringBuilder.length() - 1);

            for (SysDocumentCheckDto checkDto : documentCheckDtoList) {
                if (checkDto.getCheckType() == publicGoods.getMaterialCategory()) {
                    QualityInspectionDocumentVo qualityInspectionDocumentVo = new QualityInspectionDocumentVo();
                    qualityInspectionDocumentVo.setItemRank(checkDto.getCheckSubmit());
                    qualityInspectionDocumentVo.setCategory(publicGoods.getMaterialCategory());
                    qualityInspectionDocumentVo.setMaterialCategory(publicGoods.getMaterialType());
                    qualityInspectionDocumentVo.setMaterialCode(salesReturn.getMaterialCode());
                    qualityInspectionDocumentVo.setBatchNo(stringBuilderBatch.toString());
                    qualityInspectionDocumentVo.setAssociatedNo(salesReturn.getReceiptNo());
                    qualityInspectionDocumentVo.setDifferentString(customerManagement.getCustomerNum());
                    qualityInspectionDocumentVo.setInspectDept(SecurityUtils.getDeptId());
                    qualityInspectionDocumentVo.setModeType(12);

                    List<MaterialNumberAndBatchNoVo> materialNumberAndBatchNo = new ArrayList<>();
                    for (SalesReturnDetail entity : salesReturnDetailList) {
                        MaterialNumberAndBatchNoVo materialNumberAndBatchNoVo = new MaterialNumberAndBatchNoVo();
                        materialNumberAndBatchNoVo.setBatchNo(entity.getBatchNo());
                        materialNumberAndBatchNoVo.setMaterialNumber(entity.getMaterialNumber());
                        materialNumberAndBatchNo.add(materialNumberAndBatchNoVo);
                    }
                    qualityInspectionDocumentVo.setMaterialNumberAndBatchNo(materialNumberAndBatchNo);

                    AjaxResult add = qualityFeginService.add(qualityInspectionDocumentVo);
                    String code = add.get("code").toString();
                    if ("500".equals(code)) {
                        throw new GlobalException("生成品质检验单失败");
                    }
                }
            }
            return updateById(salesReturn);
        }
        //如果配置了交接
        if (sysDocument.getDocHandoverMark() == 1) {
            salesReturn.setStatus(4);
            return updateById(salesReturn);
        }
//            }
//        }
        salesReturn.setStatus(5);
        return updateById(salesReturn);
    }

    /**
     * 销售退货交接
     *
     * @param pickingRestDbVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PickingRestHandoverDto handover(PickingRestDbVo pickingRestDbVo) {
        PickingRestHandoverDto pickingRestHandoverDto = new PickingRestHandoverDto();
        //获取单位字典值
        List<SysDictData> unitArray = DictUtils.getDictCache("sys_material_unit");
        Map<String, String> unitMap = unitArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        SalesReturn salesReturn = getById(pickingRestDbVo.getId());
        if (salesReturn.getStatus() != 4) {
            pickingRestHandoverDto.setResultCode("500");
            pickingRestHandoverDto.setMessage("只能操作待交接的单据");
            return pickingRestHandoverDto;
        }
        //获取单据配置信息
        String menuName = "销售退货";
        Long docConfig = feignService.getIdByMenuName(menuName);
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(docConfig);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //第一步根据工号查询交接人
        if (pickingRestDbVo.getExecutionOrder() == 1) {
            //校验员工编号
            String userName = pickingRestDbVo.getInputValue();
            AjaxResult byUserName = remoteUserService.getByUserName(userName);
            SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

            if (userInfo.getUserName() == null) {
                pickingRestHandoverDto.setResultCode("500");
                pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                return pickingRestHandoverDto;
            }
            //返回交接人
//            pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
//            pickingRestHandoverDto.setDocHandoverMethod(sysDocument.getDocHandoverMethod());
//            pickingRestHandoverDto.setResultCode("200");
//            return pickingRestHandoverDto;
//        }

            //第二步
//        if (pickingRestDbVo.getExecutionOrder() == 2) {
//            SalesReturn salesReturn1 = salesReturnMapper.selectOne(new QueryWrapper<SalesReturn>().lambda().eq(SalesReturn::getReceiptNo, pickingRestDbVo.getInputValue()));
//            if (salesReturn1 == null) {
//                pickingRestHandoverDto.setResultCode("500");
//                pickingRestHandoverDto.setMessage("未查询到相关单据，请核对后输入!");
//                return pickingRestHandoverDto;
//            }
            PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, salesReturn.getMaterialCode()));


            //如果是整单
            if (sysDocument.getDocHandoverMethod() == 3) {
                BigDecimal bigDecimalNetWeight = new BigDecimal(0);
                //根据id获取明细信息
                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
                for (SalesReturnDetail entity : salesReturnDetailList) {
                    entity.setStatus(3);
                    bigDecimalNetWeight = bigDecimalNetWeight.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                }
                salesReturnDetailService.updateBatchById(salesReturnDetailList);
                //修改销售退货状态为已经完成
                salesReturn.setStatus(5);
                salesReturn.setHandoverWeight(Double.parseDouble(bigDecimalNetWeight.toString()));
                salesReturn.setHandoverNum(salesReturnDetailList.size());
                updateById(salesReturn);

                //设置出参数据
                pickingRestHandoverDto.setQuantityIdentification(salesReturn.getWarehousingWeight() + "/" + bigDecimalNetWeight + unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestHandoverDto.setOutHandoverActual(salesReturnDetailList.size() + "/" + salesReturnDetailList.size());
                pickingRestHandoverDto.setMessage("单据号:" + salesReturn.getReceiptNo() + "," + "总净重:" + bigDecimalNetWeight + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + salesReturnDetailList.size() + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }

        }

        //批次
        if (sysDocument.getDocHandoverMethod() == 2) {
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                AjaxResult byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(sysDocument.getDocHandoverMethod());
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //通过批次号查询明细数据
                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getBatchNo, pickingRestDbVo.getInputValue()));
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, salesReturnDetailList.get(0).getMaterialCode()));

                if (salesReturnDetailList.size() > 0) {
                    BigDecimal bigDecimalHand = new BigDecimal(0);
                    for (SalesReturnDetail entity : salesReturnDetailList) {
                        entity.setStatus(3);
                        bigDecimalHand = bigDecimalHand.add(new BigDecimal(String.valueOf(entity.getNetWeight())));
                    }
                    salesReturnDetailService.updateBatchById(salesReturnDetailList);
                    //修改仓库表数据
                    List<WmsStockInfo> wmsStockInfoList = wmsStockInfoMapper.selectList(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialBatch, pickingRestDbVo.getInputValue()));
                    for (WmsStockInfo info : wmsStockInfoList) {
                        info.setWsiMaterialStatus(2);
                    }
                    wmsStockInfoService.updateBatchById(wmsStockInfoList);
                    //交接重量
                    BigDecimal handoverWeight = bigDecimalHand.add(new BigDecimal(String.valueOf(salesReturn.getHandoverWeight())));

                    //交接数量
                    BigDecimal handoverNum = new BigDecimal(salesReturnDetailList.size()).add(new BigDecimal(salesReturn.getHandoverNum()));
                    //入库数量
                    List<SalesReturnDetail> detailListById = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
                    boolean isTrue = true;
                    for (SalesReturnDetail entity : salesReturnDetailList) {
                        if (entity.getStatus() != 3) {
                            isTrue = false;
                            break;
                        }
                    }
                    //如果明细都是已完成，就修改状态为已完成
                    if (isTrue) {
                        salesReturn.setStatus(5);
                    }
                    salesReturn.setHandoverWeight(Double.parseDouble(handoverWeight.toString()));
                    salesReturn.setHandoverNum(Integer.parseInt(handoverNum.toString()));
                    updateById(salesReturn);

                    //设置出参内容
                    pickingRestHandoverDto.setQuantityIdentification(salesReturn.getWarehousingWeight() + "/" + handoverWeight + unitMap.get(publicGoods.getMaterialUnit()));
                    pickingRestHandoverDto.setOutHandoverActual(detailListById.size() + "/" + handoverNum);
                    pickingRestHandoverDto.setMessage("批次号:" + pickingRestDbVo.getInputValue() + "," + "总净重:" + handoverWeight + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + salesReturnDetailList.size() + "," + "交接成功");
                    pickingRestHandoverDto.setResultCode("200");
                    return pickingRestHandoverDto;

                } else {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("没有该批次号的数据，请核实后再操作");
                    return pickingRestHandoverDto;
                }
            }
        }
        //单个物料
        if (sysDocument.getDocHandoverMethod() == 1) {
            if (pickingRestDbVo.getExecutionOrder() == 1) {
                //校验员工编号
                String userName = pickingRestDbVo.getInputValue();
                AjaxResult byUserName = remoteUserService.getByUserName(userName);
                SysUser userInfo = JSON.parseObject(JSON.toJSONString(byUserName.get("data")), SysUser.class);

                if (userInfo.getUserName() == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("交接人输入有误,请核对后输入");
                    return pickingRestHandoverDto;
                }
                //返回交接人
                pickingRestHandoverDto.setHandoverName(userInfo.getUserName() + "-" + userInfo.getNickName());
                pickingRestHandoverDto.setDocHandoverMethod(sysDocument.getDocHandoverMethod());
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
            if (pickingRestDbVo.getExecutionOrder() == 2) {
                //交接数量
                BigDecimal handoverNum = new BigDecimal(1).add(new BigDecimal(pickingRestDbVo.getHandoverNum()));

                //根据物料条码获取明细信息
                SalesReturnDetail salesReturnDetail = salesReturnDetailMapper.selectOne(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getMaterialNumber, pickingRestDbVo.getInputValue()));
                PublicGoods publicGoods = publicGoodsMapper.selectOne(new QueryWrapper<PublicGoods>().lambda().eq(PublicGoods::getMaterialCode, salesReturnDetail.getMaterialCode()));

                if (salesReturnDetail == null) {
                    pickingRestHandoverDto.setResultCode("500");
                    pickingRestHandoverDto.setMessage("只能操作待交接的单据");
                    return pickingRestHandoverDto;
                }
                //修改该明细状态为已经完成
                salesReturnDetail.setStatus(3);
                salesReturnDetailService.updateById(salesReturnDetail);
                //修改仓库表数据
                WmsStockInfo wmsStockInfo = wmsStockInfoMapper.selectOne(new QueryWrapper<WmsStockInfo>().lambda().eq(WmsStockInfo::getWsiMaterialNumber, salesReturnDetail.getMaterialNumber()));
                wmsStockInfo.setWsiMaterialStatus(2);
                wmsStockInfoService.updateById(wmsStockInfo);
                //交接重量
                BigDecimal handoverWeight = new BigDecimal(String.valueOf(salesReturnDetail.getNetWeight())).add(new BigDecimal(String.valueOf(salesReturn.getHandoverWeight())));
                //判断明细是否都已经交接成功
                List<SalesReturnDetail> salesReturnDetailList = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, pickingRestDbVo.getId()));
                boolean isTrue = true;
                for (SalesReturnDetail entity : salesReturnDetailList) {
                    if (entity.getStatus() != 3) {
                        isTrue = false;
                        break;
                    }
                }
                //如果明细都是已完成，就修改其他入库为已完成
                if (isTrue) {
                    salesReturn.setStatus(5);
                }
                salesReturn.setHandoverWeight(Double.parseDouble(handoverWeight.toString()));
                salesReturn.setHandoverNum(Integer.parseInt(handoverNum.toString()));
                updateById(salesReturn);

                //设置出参内容
                pickingRestHandoverDto.setQuantityIdentification(salesReturn.getWarehousingWeight() + "/" + handoverWeight + unitMap.get(publicGoods.getMaterialUnit()));
                pickingRestHandoverDto.setOutHandoverActual(salesReturnDetailList.size() + "/" + handoverNum);
                pickingRestHandoverDto.setMessage("物料号码:" + salesReturnDetail.getMaterialNumber() + "," + "总净重:" + salesReturnDetail.getNetWeight() + unitMap.get(publicGoods.getMaterialUnit()) + "," + "数量:" + 1 + "," + "交接成功");
                pickingRestHandoverDto.setResultCode("200");
                return pickingRestHandoverDto;
            }
        }

//            } else {
//                pickingRestHandoverDto.setResultCode("500");
//                pickingRestHandoverDto.setMessage("只能操作待交接的单据");
//                return pickingRestHandoverDto;
//            }
//        }
        return pickingRestHandoverDto;
    }


    /**
     * 销售退货品质检验回传修改数据(品质审核时fegin调用)
     *
     * @param updateStatusByQualityVo
     * @return
     */
    @Override
    public boolean updateStatusByQuality(UpdateStatusByQualityVo updateStatusByQualityVo) {
        Long menuId = feignService.getIdByMenuName("销售退货");
        AjaxResult infoDocumentConfigById = systemDocumentFeignService.getInfoDocumentConfigById(menuId);
        SysDocument sysDocument = JSON.parseObject(JSON.toJSONString(infoDocumentConfigById.get("data")), SysDocument.class);
        //获取销售退货及对应明细信息
        SalesReturn salesReturn = salesReturnMapper.selectOne(new QueryWrapper<SalesReturn>().lambda().eq(SalesReturn::getReceiptNo, updateStatusByQualityVo.getAssociatedNo()));

        List<SalesReturnDetail> salesReturnDetails = salesReturnDetailMapper.selectList(new QueryWrapper<SalesReturnDetail>().lambda().eq(SalesReturnDetail::getSalesReturnId, salesReturn.getId()));
        //如果单据状态为待检验
        if (salesReturn.getStatus() == 3) {
            //如果配置了交接
            if (sysDocument.getDocHandoverMark() == 1) {
                salesReturn.setStatus(4);
                for (SalesReturnDetail entity : salesReturnDetails) {
                    entity.setStatus(2);
                }
            } else {
                for (SalesReturnDetail entity : salesReturnDetails) {
                    entity.setStatus(3);
                }
                salesReturn.setStatus(5);
            }
        }
        if (salesReturnDetails.size() > 0) {
            salesReturnDetailService.updateBatchById(salesReturnDetails);
        }

        return updateById(salesReturn);
    }

}
